package com.car.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.account.controller.form.storesEntryForm.EntryApplicationForm;
import com.car.account.controller.form.storesEntryForm.OverruleApplicationForm;
import com.car.account.dto.geo.AddressResult2;
import com.car.account.dto.storesEntryDto.StoresEntryByIdDto;
import com.car.account.dto.storesEntryDto.StoresEntryDto;
import com.car.account.entity.*;
import com.car.account.exception.AccountException;
import com.car.account.mapper.StoresEntryApplicationMapper;
import com.car.account.param.storesEntryParam.AdminSelectEntryParam;
import com.car.account.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.car.account.util.GEOUtil;
import com.car.account.util.PageDtoUtil;
import com.car.account.util.validatorUtil.PhoneNumberValidator;
import com.car.commons.web.util.MD5util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 董旭
 * @since 2024-08-28
 */
@Service
public class StoresEntryApplicationServiceImpl extends ServiceImpl<StoresEntryApplicationMapper, StoresEntryApplication> implements StoresEntryApplicationService {

    @Resource
    private AdminService adminService;

    @Resource
    private StoresInfoService storesInfoService;

    @Resource
    private StoresService storesService;

    @Resource
    private ClerRoleService clerRoleService;

    @Resource
    private GEOUtil geoUtil;

    @Override
    public Page<StoresEntryDto> adminSelectStoresEntryDto(AdminSelectEntryParam param) throws Exception {
        //判断是否存在平台账号
        Admin admin = adminService.getById(param.getAdminId());
        if (admin == null || admin.getAdminState() == 2) throw new AccountException(5001,"平台账号不存在");
        //判断平台账号状态
        if (admin.getAdminState() == 1) throw new AccountException(5002,"平台账号已被禁用");
        //添加条件
        QueryWrapper<StoresEntryApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_name", param.getUserName()).like("user_phone", param.getUserPhone());
        if (param.getApplicationState() != null)
            queryWrapper.eq("application_state", param.getApplicationState());
        Page<StoresEntryApplication> page = new Page<>(param.getCurrent() == null ? 1 : param.getCurrent(), param.getSize() == null ? 6 : param.getSize());
        Page<StoresEntryApplication> storesEntryApplicationPage = page(page, queryWrapper);
        Page<StoresEntryDto> storesEntryDtoPage = PageDtoUtil.convertPage(storesEntryApplicationPage, StoresEntryDto.class);
        return storesEntryDtoPage;
    }

    @Override
    public StoresEntryByIdDto adminSelectById(Integer adminId, Integer applicationId) throws Exception {
        //判断是否存在平台账号
        Admin admin = adminService.getById(adminId);
        if (admin == null || admin.getAdminState() == 2) throw new AccountException(5001,"平台账号不存在");
        //判断平台账号状态
        if (admin.getAdminState() == 1) throw new AccountException(5002,"平台账号已被禁用");
        //判断是否存在申请信息
        StoresEntryApplication storesEntryApplication = getById(applicationId);
        if (storesEntryApplication == null) throw new AccountException(5003,"申请信息不存在");
        return BeanUtil.toBean(storesEntryApplication, StoresEntryByIdDto.class);
    }

    @Override
    @Transactional
    public void entryApplication(EntryApplicationForm form) throws Exception {
        if (form.getStoresName() == null || form.getUserName() == null || form.getStoresLicenseImg() == null)
            throw new AccountException(5001,"信息不完整");
        //判断手机号格式
        if (!PhoneNumberValidator.isValidPhoneNumber(form.getUserPhone())) throw new AccountException(5002,"手机号格式不正确");
        //判断手机号是否已经被绑定
        Stores storesByPhone = storesService.getOne(new QueryWrapper<Stores>()
                .eq("clerk_phone", form.getUserPhone())
                .ne("clerk_state", 2));
        if (storesByPhone != null) throw new AccountException(5003,"手机号已经被绑定");
        //判断地址格式
        geoUtil.addressConvert(form.getStoresAddress());
        //判断手机号是否有未完成的申请
        StoresEntryApplication one = getOne(new QueryWrapper<StoresEntryApplication>()
                .eq("user_phone", form.getUserPhone())
                .eq("application_state", 0));
        if (one != null)throw new AccountException(5004,"已有申请在审核中");
        //生成申请
        StoresEntryApplication storesEntryApplication = BeanUtil.toBean(form, StoresEntryApplication.class);
        storesEntryApplication.setApplicationState(0);
        save(storesEntryApplication);
    }

    @Override
    @Transactional
    public void passApplicationById(Integer adminId, Integer applicationId) throws Exception {
        //判断是否存在平台账号
        Admin admin = adminService.getById(adminId);
        if (admin == null || admin.getAdminState() == 2) throw new AccountException(5001,"平台账号不存在");
        //判断平台账号状态
        if (admin.getAdminState() == 1) throw new AccountException(5002,"平台账号已被禁用");
        //判断是否存在申请信息
        StoresEntryApplication storesEntryApplication = getById(applicationId);
        if (storesEntryApplication == null) throw new AccountException(5003,"申请信息不存在");
        //判断申请信息状态
        if (storesEntryApplication.getApplicationState() != 0) throw new AccountException(5004,"申请状态异常");
        //通过申请
        storesEntryApplication.setApplicationState(1);
        updateById(storesEntryApplication);
        //生成门店信息
        StoresInfo storesInfo = new StoresInfo();
        storesInfo.setStoresName(storesEntryApplication.getStoresName());
        storesInfo.setStoresLicenseImg(storesEntryApplication.getStoresLicenseImg());
        storesInfo.setStoresAddress(storesEntryApplication.getStoresAddress());
        AddressResult2 addressResult2 = geoUtil.addressConvert(storesEntryApplication.getStoresAddress());
        storesInfo.setLongitude(addressResult2.getLng());
        storesInfo.setLatitude(addressResult2.getLat());
        storesInfo.setStoresState(0);
        storesInfo.setCreateTime(LocalDateTime.now().toString());
        storesInfo.setScore((double) 0);
        storesInfo.setBusinessStartTime("上午9:00");
        storesInfo.setBusinessEndTime("下午6:00");
        storesInfo.setServeNum(0);
        storesInfoService.save(storesInfo);
        //生成店长信息
        Stores stores = new Stores();
        stores.setClerkName(storesEntryApplication.getUserName());
        stores.setClerkPhone(storesEntryApplication.getUserPhone());
        stores.setClerkPass(MD5util.md5(storesEntryApplication.getUserPhone(),"123456"));
        stores.setImage("https://superman-book.oss-cn-chengdu.aliyuncs.com/%E7%94%A8%E6%88%B7%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.png");
        stores.setStoresId(storesInfo.getStoresId());
        stores.setClerkState(0);
        storesService.save(stores);
        //生成店长身份
        ClerRole clerRole = new ClerRole();
        clerRole.setRoleId(1);
        clerRole.setClerkId(stores.getClerkId());
        clerRoleService.save(clerRole);
    }

    @Override
    @Transactional
    public void overruleApplicationById(Integer adminId, OverruleApplicationForm form) throws Exception {
        //判断是否存在平台账号
        Admin admin = adminService.getById(adminId);
        if (admin == null || admin.getAdminState() == 2) throw new AccountException(5001,"平台账号不存在");
        //判断平台账号状态
        if (admin.getAdminState() == 1) throw new AccountException(5002,"平台账号已被禁用");
        //判断是否存在申请信息
        StoresEntryApplication storesEntryApplication = getById(form.getApplicationId());
        if (storesEntryApplication == null) throw new AccountException(5003,"申请信息不存在");
        //判断申请信息状态
        if (storesEntryApplication.getApplicationState() != 0) throw new AccountException(5004,"申请状态异常");
        //驳回申请信息
        storesEntryApplication.setApplicationState(2);
        storesEntryApplication.setOverrule(form.getOverrule());
        updateById(storesEntryApplication);
    }
}
